import React, {Component} from 'react';
import {connect} from 'react-redux';
import {NavBar, Icon, SearchBar, List, Toast, TextareaItem, Button} from 'antd-mobile';
import QueueAnim from 'rc-queue-anim';

import { createForm } from 'rc-form';

import io from 'socket.io-client';

// import '../../assets/css/index.less';
import './style.less';

import {addAllMsg} from '../../redux/actions';

import image from '../../assets/images/头像1.png';

const Item = List.Item;


// // 连接服务器 , 得到代表连接的 socket 对象 111.67.205.4:4000
const socket = io('ws://127.0.0.1:4000');
console.log(socket);


class Tochat0 extends Component {


    constructor(props) {
        super(props);
        this.state = {
            myid: 1,
            toindex: 2,
            toid: '',
            msg: '',
            msgArray: [],
            inputValue: '',
        };
    }


    componentWillMount() {

        //获取URL中的index参数
        // let toindex = this.props.location.state.index;
        let toindex = this.props.chattingIndex;
        console.log(this.props.data[toindex]);
        let ostate = this.state;
        ostate.toindex = toindex;
        ostate.toid = this.props.data[toindex]._id;
        ostate.myid = this.props._id;
        this.setState(ostate);

        this.props.AllMsg.forEach((ele) => {
            if (ele.withId === this.state.toid) {
                let ostate = this.state;
                ostate.msgArray = ele.msg;
                this.setState(ostate);
            }
        });


        //监听来自服务器的消息
        let a = this.state.myid.toString();
        setTimeout(() => {
            console.log('tochat页面延迟1s后，连接打开');
            // let socket = io('ws://127.0.0.1:4000');
            socket.on(a, (obj) => {
                console.log('收到消息 : ', obj);
                console.log(this);
                let allmsg = this.state.msgArray;
                allmsg.push(obj);
                let proObj = this.state;
                proObj.msgArray = allmsg;
                this.setState(proObj);
                console.log(this.state);
                setTimeout(function () {
                    document.documentElement.scrollIntoView({
                        behavior: "smooth",
                        block: "end",
                        inline: "nearest"
                    });
                }, 100);


                ////////////////修改redux中的聊天记录
                let searchResult = false;
                let AllMsg = this.props.AllMsg;
                AllMsg.forEach(function (ele) {
                    if (ele.withId === obj.from || ele.withId === obj.to) {
                        ele.msg.push(obj);
                        searchResult = true;
                    }
                });
                if (searchResult === false) {
                    let a = {};
                    a.withId = obj.to;
                    a.withName = this.props.data[this.props.chattingIndex].username;
                    a.withHeader = this.props.data[this.props.chattingIndex].header;
                    a.withListIndex = this.props.chattingIndex;
                    a.msg = [];
                    a.msg.push(obj);
                    console.log(a);
                    AllMsg.push(a);
                }

                this.props.addAllMsg({AllMsg});
                console.log(this.props);
            });
        }, 100);

    }

    componentDidMount() {
        this.autoFocusInst.focus();
    }

    componentWillUnmount() {
        console.log('tochat页面unmount执行，连接close');
        // let socket = io('ws://127.0.0.1:4000');
        // socket.close();
    }

    textAreaChange = (value) =>{
        this.setState({...this.state, inputValue: value});
        console.log('textArea中的内容改变，state的值为: ',this.state);
    };


    buttonClick = (obj) => {

        // this.manualFocusInst.focus();
        let AllMsg = this.props.AllMsg;
        console.log(AllMsg, Date());
        console.log('999999999999999999999999999submit调用');
        console.log(obj);

        if (!obj.content) {
            Toast.fail('请输入内容!', 1.2);
        } else {
            socket.emit('send', obj);
            let allmsg = this.state.msgArray;
            console.log(allmsg);
            allmsg.push(obj);
            console.log(allmsg);
            let proObj = this.state;
            proObj.msgArray = allmsg;
            this.setState(proObj);
            console.log(this.state);


            // //////////////////修改redux中的聊天记录
            let searchResult2 = false;
            let AllMsg = this.props.AllMsg;
            console.log(AllMsg, Date());
            AllMsg.forEach(function (ele) {
                console.log(ele.withId === obj.to);
                if (ele.withId === obj.to) {
                    ele.msg.push(obj);
                    searchResult2 = true;
                }
            });
            if (searchResult2 === false) {
                let a = {};
                a.withId = obj.to;
                a.withName = this.props.data[this.props.chattingIndex].username;
                a.withHeader = this.props.data[this.props.chattingIndex].header;
                a.withListIndex = this.props.chattingIndex;
                a.msg = [];
                a.msg.push(obj);
                console.log(a);
                AllMsg.push(a);
            }

            console.log(AllMsg, Date());
            console.log(this.props);
            this.props.addAllMsg({AllMsg});
            console.log(this.props);
        }

        this.setState({...this.state, inputValue: ''});
        this.autoFocusInst.focus();


    };



    render() {

        const { getFieldProps } = this.props.form;

        console.log('渲染了1次');
        setTimeout(function () {
            document.documentElement.scrollIntoView({
                behavior: "smooth",
                block: "end",
                inline: "nearest"
            });
        }, 100);

        return (
            <div>


                <div className='iTopFixed'>
                    <NavBar icon={<Icon type="left"/>}
                            onLeftClick={() => window.history.go(-1)}
                            rightContent={[<Icon key="1" type="ellipsis"/>,]}
                    >{this.props.data[this.state.toindex].username}</NavBar>
                </div>
                <div style={{width: "100%", height: '50px'}}> </div>


                <div> {this.state.msgArray.map((ele, index) => (
                    <QueueAnim className="queue-simple" key={index}>
                        <div style={{width: '100%', lineHeight: '40px', fontSize: '18px'}} key={index}>
                            <img className={ele.from === this.state.myid ? 'rightImg' : 'leftImg'}
                                 src={image}/>
                            <div className={ele.from === this.state.myid ? 'rightText' : 'leftText'}>
                                {ele.content}</div>
                        </div>
                    </QueueAnim>
                ))}
                </div>


                <div style={{width: "100%", height: '100px'}}> </div>

                <div className={'inputBar'}>

                    <div className={'input'}>
                        <TextareaItem rows={2}
                                      ref={el => this.autoFocusInst = el}
                                      value={this.state.inputValue}
                                      onChange={(value) => this.textAreaChange(value)}/>
                    </div>


                    <div className={'button'}
                         onClick={()=> this.buttonClick({
                             content: this.state.inputValue,
                             from: this.state.myid,
                             to: this.props.data[this.state.toindex]._id})
                         }>
                        发送
                    </div>


                </div>

            </div>

        )
    }
}

const Tochat = createForm()(Tochat0);

export default connect(
    state => state.user,
    {addAllMsg}
)(Tochat)